package cn.wolfcode.Shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.exception.MyException;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.mapper.PermissionMapper;
import cn.wolfcode.mapper.RoleMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class CrmRea1m extends AuthorizingRealm {
    @Autowired
    private EmployeeMapper mapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    //将容器中的配置的凭证匹配器注入给当前的Realm对象

//在该Realm中使用指定的凭证匹配器来完成密码匹配的操作

    @Autowired
    public void setCredentialsMatcher(CredentialsMatcher credentialsMatcher) {

        super.setCredentialsMatcher(credentialsMatcher);

    }

    /*
          shiro中的认证的方法
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("+++++++++++++++++++++++++++++++++");
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        Employee employee = mapper.SelectEmployeeByName(username);

        if (employee != null) {
            if (!employee.isStatus()) {
                /*throw new MyException("账号已经被注销,请联系管理员");*/
                throw  new  AuthenticationException("账号已经被注销,请联系管理员");
            } else {
                return new SimpleAuthenticationInfo(employee, employee.getPassword(), ByteSource.Util.bytes(employee.getName()), this.getName());
            }
        }
        return null;
    }


    /*
        shiro中的授权方法
    */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Employee employee = (Employee) principalCollection.getPrimaryPrincipal();   //获取主体
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        if (!employee.isAdmin()) {
            //查找员工的角色
            List<String> list = roleMapper.selRolesByEmpId(employee.getId());
            //查找员工的权限
            List<String> expression = permissionMapper.getExpressionByEmpId(employee.getId());
            info.addStringPermissions(expression);
            info.addRoles(list);

        } else {
            info.addStringPermission("*:*");
            info.addRole("admin");
        }

        return info;
    }
}
